package com.example.billw.controller;

import com.example.billw.entity.Users;
import com.example.billw.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.List;

@Controller
public class UsersController {

    @Autowired
    private UserMapper userMapper;


    @RequestMapping("/users")
    public String userList(Model model, Users users) {
        List<Users> usersList = userMapper.getUsers(users);
        model.addAttribute("users", usersList);
        model.addAttribute("username", users.getUsername());
        return "user/list";
    }

    @RequestMapping("/user/{id}")
    public String viewUser(@PathVariable("id") int id,
                           @RequestParam(value = "type", required = false, defaultValue = "view") String type,
                           Model model) {
        Users users = userMapper.getUserById(id);
        model.addAttribute("user", users);
        return "user/" + type;
//        return "user/view";
    }

    @RequestMapping("/user/update")
    public String update(Users users) {
        userMapper.updateUser(users);
        return "redirect:/users";
    }
    @PostMapping("/user")
    public String add(Users users) {
        userMapper.addUser(users);
        return "redirect:/users";
    }

    @PostMapping("/user/delete/{id}")
    public String delete(@PathVariable("id") int id,HttpServletRequest request) {
        Users loginUser = (Users) request.getSession().getAttribute("loginUser");
        if (loginUser.getId().equals(id)){
            return "redirect:/users";
        }
        userMapper.deleteUser(id);
        return "redirect:/users";
    }

    @GetMapping("/user/pwd")
    public String toPwdPage(){
        return "main/password";
    }

    @ResponseBody
    @GetMapping("/user/pwd/{oldPwd}")
    public Boolean checkPwd(HttpServletRequest request, @PathVariable("oldPwd") String oldPwd){
        Users loginUser = (Users) request.getSession().getAttribute("loginUser");
        if (oldPwd.equals(loginUser.getPassword())) {
            return true;
        }else{
            return false;
        }
    }

    @PostMapping("/user/pwd")
    public String updatePwd(HttpSession session,String password){
        Users user = (Users) session.getAttribute("loginUser");
        user.setPassword(password);
        userMapper.updateUserPwd(user);

        return "redirect:/";
    }
    @GetMapping("/user")
    public String toAddPage(){
        return "user/add";
    }
}
